package com.bdqn.systems.service.impl;

import com.bdqn.systems.entity.User;
import com.bdqn.systems.mapper.MenuMapper;
import com.bdqn.systems.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * @author : CP
 * @version: 1.0
 * @program : xinguan-parent
 * @description : 我的用户详细信息服务
 * @date : 2020-12-23 10:32
 **/
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 通过用户名加载用户
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //创建权限集
        List<GrantedAuthority> authorities = new ArrayList<>();

        //判断用户
        User user = userService.selectByName(s);
        if(user == null){
            throw new UsernameNotFoundException(String.format("%s用户不存在",s));
        }

        List<String> menus = menuMapper.userMenuPermissions(s);
        //过滤空值
        menus = menus.parallelStream()
                .filter(Objects::nonNull)
                .filter(s1 -> !s.isEmpty())
                .collect(Collectors.toList());

        menus.forEach(menu ->{
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_"+menu);
            authorities.add(simpleGrantedAuthority);
        });

        return new org.springframework.security.core.userdetails.User(s,user.getPassword(),authorities);
    }
}
